//
//  AppDelegate.m
//  Demo
//
//  Created by 龚碧容 on 2017/9/15.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "AppDelegate.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import <UMSocialCore/UMSocialCore.h>
#import <CoreData/CoreData.h>
#import <WXApi.h>

#import "QLBxOrderCostVC.h"
#import "QLMBXOrderDetailVC.h"

#import "FirstVC.h"

// 引入JPush功能所需头文件
#import <JPUSHService.h>
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

static NSString *jpushAppKey = @"a5429f9e2b9b0628585f7473";
static NSString *jpushChannel= @"App Store";
static BOOL isProduction = TRUE;//FALSE;

@interface AppDelegate ()<WXApiDelegate,EAIntroDelegate,BMKGeneralDelegate,JPUSHRegisterDelegate,UIAlertViewDelegate>

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    BMKMapManager *mapManager = [[BMKMapManager alloc]init];
    if ([BMKMapManager setCoordinateTypeUsedInBaiduMapSDK:BMK_COORDTYPE_BD09LL]) {
        NSLog(@"经纬度类型设置成功");
    } else {
        NSLog(@"经纬度类型设置失败");
    }
    BOOL ret = [mapManager start:@"tQmMv4FaSYdFqmgl5kiTwBeqXcw44NY0" generalDelegate:self];//
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    
    [self _setupNotification:launchOptions];
    
    /* 打开调试日志 */
    [[UMSocialManager defaultManager] openLog:YES];
    /* 设置友盟appkey */
    [[UMSocialManager defaultManager] setUmSocialAppkey:@"59d83f9faed179268b00002f"];
    [self configUSharePlatforms];
    [self confitUShareSettings];
    
    UMConfigInstance.appKey = @"59d83f9faed179268b00002f";
    UMConfigInstance.channelId = @"App Store";
    [MobClick startWithConfigure:UMConfigInstance];//配置以上参数后调用此方法初始化SDK！
    
    [WXApi registerApp:@"wxe3ab42ed16fff91a"];//向微信注册
    [self setupMainUI];
    [self _setupIQKeyBoardSetting];
    
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"isFirstLanch"]){
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isFirstLanch"];
        NSLog(@"第一次启动");
        [self showIntroWithCrossDissolve];
    }
    [ClientTool aFNetworkStatus];
    
    NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if(userInfo){//推送信息
        _pushUserInfo = userInfo[@"extras"];//[userInfo copy]
    }
    
    return YES;
}

- (void)_setupIQKeyBoardSetting{
    IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager]; // 获取类库的单例变量
    keyboardManager.enable = YES; // 控制整个功能是否启用
    keyboardManager.shouldResignOnTouchOutside = YES; // 控制点击背景是否收起键盘
    keyboardManager.shouldToolbarUsesTextFieldTintColor = YES; // 控制文字颜键盘上的工具条色是否用户自定义
    keyboardManager.toolbarManageBehaviour = IQAutoToolbarBySubviews; // 有多个输入框时，可以通过点击Toolbar 上的“前一个”“后一个”按钮来实现移动到不同的输入框
    keyboardManager.enableAutoToolbar = YES; // 控制是否显示键盘上的工具条
    keyboardManager.shouldShowToolbarPlaceholder = NO; // 是否显示占位文字
    keyboardManager.placeholderFont = [UIFont boldSystemFontOfSize:17]; // 设置占位文字的字体
    keyboardManager.keyboardDistanceFromTextField = 10.0f; // 输入框距离键盘的距离
}

- (void)_setupNotification:(NSDictionary *)launchOptions{
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
#endif
    }else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    }
    
    [JPUSHService setupWithOption:launchOptions appKey:jpushAppKey
                          channel:jpushChannel
                 apsForProduction:isProduction
            advertisingIdentifier:nil];
    
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidSetup:)
                          name:kJPFNetworkDidSetupNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidClose:)
                          name:kJPFNetworkDidCloseNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidRegister:)
                          name:kJPFNetworkDidRegisterNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidLogin:)
                          name:kJPFNetworkDidLoginNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidReceiveMessage:)
                          name:kJPFNetworkDidReceiveMessageNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(serviceError:)
                          name:kJPFServiceErrorNotification
                        object:nil];
}

- (UITabBarItem *)aselectWithTitle:(NSString *)title image:(NSString *)imgName tag:(NSInteger)tag{
    
    UITabBarItem *tabBarItem=[[UITabBarItem alloc] initWithTitle:title image:[UIImage imageNamed:imgName] tag:tag];
    NSMutableDictionary *attrSelected = [NSMutableDictionary dictionary];
    attrSelected[NSFontAttributeName] = [UIFont systemFontOfSize:16];
    attrSelected[NSForegroundColorAttributeName] = kNavigationBarColor;
    [tabBarItem setTitleTextAttributes:attrSelected forState:UIControlStateSelected];
    return tabBarItem;
}

- (UINavigationController *)_setupTabbarItem:(UITabBarItem *)tabBarItem andViewCtr:(UIViewController *)viewCtr andImage:(NSString *)imgName andSelectImage:(NSString *)selImageName{
    
    UIImage *img1 = [UIImage imageNamed:imgName];
    UIImage *imgS1 =[UIImage imageNamed:selImageName];
    
    UIEdgeInsets insets = UIEdgeInsetsMake(6, 0, -6, 0);
    UINavigationController *nav=[[UINavigationController alloc] initWithRootViewController:viewCtr];
    nav.navigationBar.barTintColor=kNavigationBarColor;
    nav.tabBarItem=tabBarItem;
    nav.tabBarItem.imageInsets = insets;
    
    nav.tabBarItem.selectedImage = [imgS1 imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    nav.tabBarItem.image = [img1 imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    [nav.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    nav.navigationBar.translucent=NO;
    
    return nav;
}

- (void)setupMainUI{
    
    UITabBarItem *tabBarItem1=[self aselectWithTitle:@"首页" image:@"tb_home"   tag:0];
    UITabBarItem *tabBarItem2=[self aselectWithTitle:@"报修" image:@"tb_baoxiu" tag:1];
    UITabBarItem *tabBarItem3=[self aselectWithTitle:@"设备" image:@"tb_shebei" tag:2];
    UITabBarItem *tabBarItem4=[self aselectWithTitle:@"我的" image:@"tb_wode"   tag:3];
    
    ViewController *viewCtr = [[ViewController alloc]init];
    UINavigationController *navCtr1 = [self _setupTabbarItem:tabBarItem1 andViewCtr:viewCtr andImage:@"tb_home" andSelectImage:@"tb_home_s"];
    
    _secondViewCtr=[[SecondViewController alloc] init];
    UINavigationController *navCtr2 = [self _setupTabbarItem:tabBarItem2 andViewCtr:_secondViewCtr andImage:@"tb_baoxiu" andSelectImage:@"tb_baoxiu_s"];
    
    _thirdViewCtr=[[ThirdViewController alloc] init];
    UINavigationController *navCtr3 = [self _setupTabbarItem:tabBarItem3 andViewCtr:_thirdViewCtr andImage:@"tb_shebei" andSelectImage:@"tb_shebei_s"];
    
    _fourtnViewCtr=[[FourthViewController alloc] init];
    UINavigationController *navCtr4 = [self _setupTabbarItem:tabBarItem4 andViewCtr:_fourtnViewCtr andImage:@"tb_wode" andSelectImage:@"wode_sel"];

    _tabbarController=[[UITabBarController alloc] init];
    _tabbarController.viewControllers=[NSArray arrayWithObjects:navCtr1,navCtr2,navCtr3,navCtr4, nil];
    _tabbarController.selectedIndex=0;
    _tabbarController.tabBar.barTintColor=[UIColor whiteColor];
    
    self.window.rootViewController=_tabbarController;
}

- (void)showIntroWithCrossDissolve{
    
    EAIntroPage *page1 = [EAIntroPage page];
    page1.bgImage = [UIImage imageNamed:@"intro1"];
    
    EAIntroPage *page2 = [EAIntroPage page];
    page2.bgImage = [UIImage imageNamed:@"intro2"];
    
    EAIntroPage *page3 = [EAIntroPage page];
    page3.bgImage = [UIImage imageNamed:@"intro3"];
    
    EAIntroPage *page4 = [EAIntroPage page];
    page4.bgImage = [UIImage imageNamed:@"intro4"];
    
    EAIntroPage *page5 = [EAIntroPage page];
    page5.bgImage = [UIImage imageNamed:@"intro5"];
    
    EAIntroView *intro = [[EAIntroView alloc] initWithFrame:self.window.bounds andPages:@[page1,page2,page3,page4,page5]];
    intro.skipButtonAlignment = EAViewAlignmentCenter;
    intro.skipButtonY = kScreen_height-kScreen_height+85.f;
    
    intro.skipButton.layer.masksToBounds=YES;
    intro.skipButton.layer.cornerRadius=5.0f;
    intro.skipButton.backgroundColor=UIColorFromRGB(0xffae00);
    
    intro.skipButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    [intro.skipButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    intro.pageControlY = 42.f;
    [intro setDelegate:self];
    [intro.skipButton setTitle:@"立即体验" forState:UIControlStateNormal];
    [intro showInView:self.window.rootViewController.view animateDuration:0.3];
}

#pragma mark - 跳转界面
- (void)pushToLoginerUidCorret{
    UIAlertView *alertV=[[UIAlertView alloc] initWithTitle:@"消息提醒" message:@"您的报修订单状态已更新，是否前往查看？" delegate:self cancelButtonTitle:@"稍后" otherButtonTitles:@"立即前往", nil];
    [alertV show];
}

- (void)requRepairOrder{
    NSMutableDictionary *paramerDic=[NSMutableDictionary dictionary];
    [paramerDic setObject:_pushUserInfo[@"repairOrderId"] forKey:@"repairOrderId"];
    [ClientTool postUrlPath:@"/test/repairOrder/orderInfo" withParamers:paramerDic andBody:nil
                    success:^(id responseObject){
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            
                            QLMOrderListInfoModel *resultInfoModel=[[QLMOrderListInfoModel alloc] initWithDictionary:responseObject[@"repairOrder"] error:nil];
                            [self pushToOrderDetailVC:resultInfoModel];
                            
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        ETToast(@"服务器连接失败");
                    }
     ];
}

- (void)pushToOrderDetailVC:(QLMOrderListInfoModel *)resultOrderModel{
    UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
    UINavigationController *nav = (UINavigationController *)tabBarController.selectedViewController;
    UIViewController *baseVC = (UIViewController *)nav.visibleViewController;
    
    QLMBXOrderDetailVC *messageVC = [QLMBXOrderDetailVC new];
    messageVC.repairOrderId=_pushUserInfo[@"repairOrderId"];
    messageVC.resultInfoModel=resultOrderModel;
    messageVC.isPushJumpBool=YES;
    baseVC.hidesBottomBarWhenPushed=YES;
    [nav pushViewController:messageVC animated:YES];
    baseVC.hidesBottomBarWhenPushed=NO;
}

#pragma mark - UIAlertView delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==1) {
        UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
        UINavigationController *nav = (UINavigationController *)tabBarController.selectedViewController;
        UIViewController *baseVC = (UIViewController *)nav.visibleViewController;
        
        if ([[UserManager sharedManager] isUserLogin]) {//判断用户是否登录
            //如果当前控制器是QLMBXOrderDetailVC，刷新数据即可
            if([baseVC isKindOfClass:[QLMBXOrderDetailVC class]]){
                QLMBXOrderDetailVC *vc = (QLMBXOrderDetailVC *)baseVC;
                [vc requRepairOrder];
                return;
            }
            //否则，跳转到QLMBXOrderDetailVC
            [self requRepairOrder];
            
        }else{
            QLMLoginViewController *loginController = [QLMLoginViewController new];
            loginController.pushUid=_pushUserInfo[@"userId"];
            loginController.resultBlock=^(BOOL success){};
            QLMCustomNavCtr *nav123=[[QLMCustomNavCtr alloc] initWithRootViewController:loginController];
            [nav presentViewController:nav123 animated:YES completion:nil];
        }
    }
}

#pragma mark - InterfaceOrientation //应用支持的方向
- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    if (_allowRotate == 1) {
        return UIInterfaceOrientationMaskAllButUpsideDown;
    }else{
        return UIInterfaceOrientationMaskPortrait;
    }
}

// 返回是否支持设备自动旋转
- (BOOL)shouldAutorotate {
    if (_allowRotate == 1) {
        return YES;
    } return NO;
}

#pragma mark - Coredata
//托管对象
-(NSManagedObjectModel *)managedObjectModel{
    if (_managedObjectModel!=nil) {
        return _managedObjectModel;
    }
    _managedObjectModel=[NSManagedObjectModel mergedModelFromBundles:nil];
    return _managedObjectModel;
}

//托管对象上下文
-(NSManagedObjectContext *)managedObjectContext{
    if (_managedObjectContext!=nil) {
        return _managedObjectContext;
    }
    NSPersistentStoreCoordinator *coordinator=[self persistentStoreCoordinator];
    if (coordinator!=nil) {
        _managedObjectContext=[[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

//持久化存储协调器
-(NSPersistentStoreCoordinator *)persistentStoreCoordinator{
    
    if (_persistentStoreCoordinator!=nil) {
        return _persistentStoreCoordinator;
    }
    
    NSString *docs=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSURL* storeURL=[NSURL fileURLWithPath:[docs stringByAppendingPathComponent:@"homeData.sqlite"]];
//    NSLog(@"path is %@",storeURL);
    NSError *error=nil;
    _persistentStoreCoordinator=[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        NSLog(@"Error: %@,%@",error,[error userInfo]);
    }
    return _persistentStoreCoordinator;
}

#pragma mark - share settings
- (void)confitUShareSettings{
    [UMSocialGlobal shareInstance].isUsingHttpsWhenShareContent = NO;
}

- (void)configUSharePlatforms{
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wxe3ab42ed16fff91a" appSecret:@"3baf1193c85774b3fd9d18447d76cab0" redirectURL:nil];
    [[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite)]];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"1106467043" appSecret:nil redirectURL:@"http://mobile.umeng.com/social"];
    
    [[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_DingDing)]];
    
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_DingDing appKey:@"dingoak5hqhuvmpfhpnjvt" appSecret:nil redirectURL:nil];
    
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:@"3921700954"  appSecret:@"04b48b094faeb16683c32669824ebdad" redirectURL:@"https://sns.whalecloud.com/sina2/callback"];
}

#pragma mark - 推送回调方法
- (void)networkDidSetup:(NSNotification *)notification {
    NSLog(@"已连接");
}

- (void)networkDidClose:(NSNotification *)notification {
    NSLog(@"未连接");
}

- (void)networkDidRegister:(NSNotification *)notification {
    NSLog(@"%@", [notification userInfo]);
    NSLog(@"已注册");
}

- (void)networkDidLogin:(NSNotification *)notification {
    
    NSLog(@"已登录");////////消息收不到是证书有问题////////////////
    if ([[UserManager sharedManager] isUserLogin]) {
        NSString *userId=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginUserId];
        NSString *auserId = [NSString stringWithFormat:@"%@",userId];
        [JPUSHService setAlias:auserId completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
            NSLog(@"iAlias = %@",iAlias);
        } seq:0];
    }
    
    if ([JPUSHService registrationID]){
        NSLog(@"get RegistrationID");
    }
}

- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSString *repairOrderId=[NSString stringWithFormat:@"%@",[userInfo[@"extras"] objectForKey:@"repairOrderId"]];
    _pushUserInfo=userInfo[@"extras"];
    if ([self isNull:repairOrderId]) {
        [self pushToLoginerUidCorret];
    }
}

- (void)serviceError:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSString *error = [userInfo valueForKey:@"error"];
    NSLog(@"%@", error);
}

- (BOOL)isNull:(id)object{
    // 判断是否为空串
    if ([object isEqual:[NSNull null]]) {
        return NO;
    }else if ([object isKindOfClass:[NSNull class]]){
        return NO;
    }else if (object==nil){
        return NO;
    }
    return YES;
}

#pragma mark -
// 支持所有iOS系统
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result) {
        // 其他如支付等SDK的回调
        if ([url.host isEqualToString:@"safepay"] || [url.host hasPrefix:@"platformapi"]) {
            //跳转支付宝钱包进行支付，处理支付结果
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
                NSLog(@"result = %@",resultDic);
                
                NSInteger status = [[resultDic objectForKey:@"resultStatus"] integerValue];
                if (status == 9000) {
                    ETToast(@"支付成功");
                    [self pushToOrderCostVC];
                }else if(status == 8000){
                    ETToast(@"正在处理中");
                }else if(status == 4000){
                    ETToast(@"支付失败");
                }else if(status == 6001){
                    ETToast(@"取消支付");
                }else if(status == 5000){
                    ETToast(@"重复请求");
                }
                
            }];
        }else{
            return [WXApi handleOpenURL:url delegate:self];
        }
    }
    return result;
}


#pragma mark -jpush appdelegate
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required - 注册 DeviceToken
    NSLog(@"deviceToken = %@",deviceToken);
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:
(UIUserNotificationSettings *)notificationSettings {
}

- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forLocalNotification:(UILocalNotification *)notification
  completionHandler:(void (^)())completionHandler {
}

- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forRemoteNotification:(NSDictionary *)userInfo
  completionHandler:(void (^)())completionHandler {
}
#endif

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"iOS6及以下系统，收到通知:%@", userInfo);
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"iOS7及以上系统，收到通知:%@", userInfo);
    
    if ([[UIDevice currentDevice].systemVersion floatValue]<10.0 || application.applicationState>0) {
        
    }
    
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
}

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        NSLog(@"iOS10 收到远程通知:%@", userInfo);
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    
    completionHandler();  // 系统要求执行这个方法
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        NSLog(@"iOS10 前台收到远程通知:%@",userInfo);
        //        [self goToMssageViewControllerWith:userInfo];
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
    
}
#endif

#pragma mark - 支付
// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options{
    
    NSLog(@"result123 = %@",url);
    
    if ([url.host isEqualToString:@"safepay"] || [url.host hasPrefix:@"platformapi"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            
            NSInteger status = [[resultDic objectForKey:@"resultStatus"] integerValue];
            if (status == 9000) {
                ETToast(@"支付成功");
                [self pushToOrderCostVC];
            }else if(status == 8000){
                ETToast(@"正在处理中");
            }else if(status == 4000){
                ETToast(@"支付失败");
            }else if(status == 6001){
                ETToast(@"取消支付");
            }else if(status == 5000){
                ETToast(@"重复请求");
            }
            
        }];
    }else if([url.host isEqualToString:@"response_from_qq"]){
        if ([[url absoluteString] containsString:@"error=0"]) {
            ETToast(@"QQ分享成功");
            [self changeVipNumData];
        }else{
            ETToast(@"QQ分享取消");
        }
    }else{
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    return [WXApi handleOpenURL:url delegate:self];
}

#pragma mark - WXApiDelegate
-(void)onResp:(BaseResp *)resp{
    if ([resp isKindOfClass:[PayResp class]]) {
        PayResp*response=(PayResp*)resp;  // 微信终端返回给第三方的关于支付结果的结构体
        switch (response.errCode) {
            case WXSuccess:
            {// 支付成功，向后台发送消息
                NSLog(@"支付成功");
                [[NSNotificationCenter defaultCenter] postNotificationName:@"WX_PaySuccess" object:nil];
                [self pushToOrderCostVC];
            }
                break;
            case WXErrCodeCommon:
            { //签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等
                ETToast(@"支付失败");
            }
                break;
            case WXErrCodeUserCancel:
            { //用户点击取消并返回
                ETToast(@"取消支付");
            }
                break;
            case WXErrCodeSentFail:
            { //发送失败
                ETToast(@"发送失败");
            }
                break;
            case WXErrCodeUnsupport:
            { //微信不支持
                ETToast(@"微信不支持");
            }
                break;
            case WXErrCodeAuthDeny:
            { //授权失败
                ETToast(@"授权失败");
            }
                break;
            default:
                break;
        }
    }else{
        SendMessageToWXResp *respon=(SendMessageToWXResp*)resp;
        if (respon.errCode==0) {
            ETToast(@"微信分享成功");
            [self changeVipNumData];
        }else{
            ETToast(@"微信分享取消");
        }
    }
}

- (void)changeVipNumData{
    NSString *vipNumber=[[NSUserDefaults standardUserDefaults] objectForKey:kVipNumber];
    NSMutableDictionary *paramDic=[NSMutableDictionary dictionary];
    [paramDic setObject:vipNumber forKey:@"vipNumber"];
    [ClientTool postUrlPath:@"/rest/vipInfo/addXiaomaBeenForAppShare" withParamers:paramDic andBody:nil
                    success:^(id responseObject){
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
//                            NSLog(@"responseObject = %@",responseObject);
                            [_fourtnViewCtr reuqestUserInfoData];
                            
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        ETToast(@"服务器连接失败");
                    }
     ];
}

#pragma mark - 支付成功后跳转到费用详情界面 pushToOrderCostVC
- (void)pushToOrderCostVC{
    for (UIViewController *VC in [self currentViewController].navigationController.viewControllers) {
        if ([VC isKindOfClass:[QLBxOrderCostVC class]]) {
            QLBxOrderCostVC *costVC=(QLBxOrderCostVC *)VC;
            costVC.isBXPayMoneyJumpBool=YES;
            [[self currentViewController].navigationController popToViewController:VC animated:YES];
        }
    }
}

-(UIViewController*)findBestViewController:(UIViewController*)vc {
    if (vc.presentedViewController) {
        // Return presented view controller
        return [self findBestViewController:vc.presentedViewController];
    } else if ([vc isKindOfClass:[UISplitViewController class]]) {
        // Return right hand side
        UISplitViewController* svc = (UISplitViewController*) vc;
        if (svc.viewControllers.count > 0){
            return [self findBestViewController:svc.viewControllers.lastObject];
        }else{
            return vc;
        }
    } else if ([vc isKindOfClass:[UINavigationController class]]) {
        // Return top view
        UINavigationController* svc = (UINavigationController*) vc;
        if (svc.viewControllers.count > 0){
            return [self findBestViewController:svc.topViewController];
        }else{
            return vc;
        }
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        // Return visible view
        UITabBarController* svc = (UITabBarController*) vc;
        if (svc.viewControllers.count > 0){
            return [self findBestViewController:svc.selectedViewController];
        }else{
            return vc;
        }
    } else {
        // Unknown view controller type, return last child view controller
        return vc;
    }
}

-(UIViewController*)currentViewController{
    // Find best view controller
    UIViewController* viewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    return [self findBestViewController:viewController];
}

@end
